<template>
	<view class="container">
		<text class="title">Map Topic Payload</text>
		<scroll-view scroll-y class="box">
			<text selectable>{{ displayText }}</text>
		</scroll-view>
		<button type="primary" @click="requestMap">请求地图(get slam_map_control)</button>
	</view>
</template>

<script>
import { connectMqtt, subscribe, unsubscribe, publishMessage } from '@/services/mqttService';

export default {
	data() {
		return {
			mapPayload: '',
			subscribed: false
		};
	},
	onLoad() {
		this.init();
	},
	onUnload() {
		this.cleanup();
	},
	computed: {
		displayText() {
			return this.mapPayload || '暂无数据';
		}
	},
	methods: {
		async init() {
			this._mapHandler = (topic, msg) => {
				try {
					const str = msg.toString();
					this.mapPayload = str;
					console.log(topic)
				} catch (e) {
					this.mapPayload = String(msg);
				}
			};
			try {
				await connectMqtt();
				subscribe('scan', this._mapHandler);
				this.subscribed = true;
				// 首次进入页面后立即请求一次地图
				this.requestMap();
			} catch (e) {
				uni.showToast({ title: 'MQTT 连接失败', icon: 'none' });
			}
		},
		requestMap() {
			const payload = {
				cmd: 'get',
				cmd_type: 'slam_map_control'
			};
			const ok = publishMessage('robot_control', JSON.stringify(payload));
			if (!ok) {
				uni.showToast({ title: '发送失败，稍后自动重试', icon: 'none' });
			}
		},
		cleanup() {
			if (this.subscribed && this._mapHandler) {
				unsubscribe('map', this._mapHandler);
				this.subscribed = false;
			}
		}
	}
}
</script>

<style>
.container { padding: 16rpx; }
.title { font-size: 32rpx; margin-bottom: 16rpx; }
.box { height: 400rpx; background: #f7f7f7; padding: 12rpx; border-radius: 8rpx; }
</style>
